//
//  XYMutableDictionary.m
//  PeiZhuShou
//
//  Created by 找汽配 on 16/9/18.
//  Copyright © 2016年 XiangYun. All rights reserved.
//

#import "XYMutableDictionary.h"
#import "NSString+XY.h"

@interface XYMutableDictionary ()

@property (nonatomic, strong) NSMutableDictionary * mutableDictionary;

@end

@implementation XYMutableDictionary

+ (instancetype)dictionary {
    return [[XYMutableDictionary alloc] init];
}

- (instancetype)init {
    self = [super init];
    if (self) {
        self.mutableDictionary = [NSMutableDictionary dictionary];
    }
    return self;
}

- (void)setObject:(id)anObject forKey:(id<NSCopying>)aKey {
    if (anObject && aKey) {
        [self.mutableDictionary setObject:anObject forKey:aKey];
    }
}

- (void)removeObjectForKey:(id)aKey {
    if (aKey) {
        [self.mutableDictionary removeObjectForKey:aKey];
    }
}

- (NSMutableDictionary *)mutableDictionary {
    return _mutableDictionary;
}

- (NSDictionary *)dictionary {
    return [_mutableDictionary copy];
}

- (NSString *)urlQueryWithEncoded:(BOOL)encoded {
    // NOTE: 排序，得出最终请求字串
    NSArray * sortedKeyArray = [[_mutableDictionary allKeys] sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj1 compare:obj2];
    }];
    
    NSMutableArray * mArray = [NSMutableArray arrayWithCapacity:sortedKeyArray.count];
    for (NSString * key in sortedKeyArray) {
        [mArray addObject:[self stringWithKey:key value:_mutableDictionary[key] encoded:encoded]];
    }
    return [mArray componentsJoinedByString:@"&"];
}

- (NSString *)stringWithKey:(NSString *)key value:(NSString *)value encoded:(BOOL)encoded {
    return [NSString stringWithFormat:@"%@=%@", key, (encoded ? [value urlQueryEncode] : value)];
}

@end
